package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.CustomException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.SysUserService;
import com.itheima.ydd.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @autehor yuan
 * @date 2022/11/12
 * @Description   基础模块,后台
 */
@RestController
@RequestMapping("/index")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录
     * @param sysUser
     * @return
     */
    @PostMapping("login")
    public R login(HttpServletRequest request,@RequestBody SysUser sysUser){
        //1. 根据用户名查询数据库,判断是否存在该用户: 不存在则直接抛出异常
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLogin_name,sysUser.getLogin_name());
        SysUser user = sysUserService.getOne(wrapper);
        if (user == null)
            throw new CustomException("用户信息不存在!");
        //2. 判断用户密码是否正确: 不正确则直接抛出异常
        String pwd = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        if (!pwd.equals(user.getPassword()))
            throw new CustomException("密码错误!");

        //3. 判断用户状态是否正常: 不正常则直接抛出异常
        if (user.getStatus() == 0){
            throw new CustomException("该账户已冻结!");
        }

        //4. 更新用户的最后登录时间和最后登录ip
        user.setLogin_ip(request.getRemoteAddr());
        user.setLogin_date(new Date());
        sysUserService.updateById(user);

        //5. 登录成功,返回token
        Map<String,Object> tokenMap = new HashMap<>();
        //将当前用户的id和对应的角色id写入token中
        tokenMap.put("userId",user.getId());
        tokenMap.put("roldId",user.getRole_id());
        String token = JwtUtils.getToken(tokenMap);

        Map<String,Object> resMap = new HashMap<>();
        resMap.put("token",token);
        return R.success(resMap);
    }
}
